﻿using System;
using System.Data;

namespace VitCode.Castle.Helper
{
    /// <summary>
    /// CharConvertHelper 的摘要說明。
    /// </summary>
    public class CharConvertHelper
    {
        public CharConvertHelper()
        {
            //
            // TODO: 在此處添加構造函數邏輯
            //
        }

        /// <summary>
        /// 轉全形的函數(SBC case)
        /// </summary>
        /// <param name="input">任意字串</param>
        /// <returns>全形字串</returns>
        ///<remarks>
        ///全形空格為12288，半形空格為32
        ///其他字元半形(33-126)與全形(65281-65374)的對應關係是：均相差65248
        ///</remarks>        
        public string ToSBC(string input)
        {
            //半形轉全形：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char) 12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char) (c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// 轉半形的函數(DBC case)
        /// </summary>
        /// <param name="input">任意字串</param>
        /// <returns>半形字串</returns>
        ///<remarks>
        ///全形空格為12288，半形空格為32
        ///其他字元半形(33-126)與全形(65281-65374)的對應關係是：均相差65248
        ///</remarks>
        public string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char) 32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char) (c[i] - 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// 把DataTable資料中的全形字符轉成半形
        /// </summary>
        /// <param name="source">資料源DataTable</param>
        /// <returns>修改後的資料源DataTable</returns>
        public DataTable ToDBC(DataTable source)
        {
            if(source != null && source.Rows.Count > 0)
            {
                foreach(DataRow row in source.Rows)
                {
                    for(int i=0;i<source.Columns.Count;i++)
                    {
                        string strTemp = Convert.ToString(row[i]);
                        if(strTemp.Length > 0)
                            row[i]=ToDBC(strTemp);
                    }
                }
            }
            return source;
        }
    }
}
